package com.cn.common;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class MessageCheckout {

    public static List<MessageExt> decodeMessage(PullResult pullResult) {
        List<MessageExt> list = new ArrayList<>();
        if (pullResult.getBodys() == null) {
            return list;
        }
        ByteBuffer byteBuffer = ByteBuffer.wrap(pullResult.getBodys());
        int size = 0;
        boolean flag = true;

        while (flag) {
            if (size == (int) pullResult.getTotalMsgSize()) {
                break;
            }
            MessageExt messageExt = new MessageExt();

            int totalSize = byteBuffer.getInt();//4位TOTALSIZE
            if (totalSize <= 0) flag = false;
            messageExt.setTotalSize(totalSize);//本条消息大小

            // 2. topic长度
            byte topicLength = byteBuffer.get();

            //3. topic内容
            byte[] topics = new byte[topicLength];
            byteBuffer.get(topics);
            messageExt.setTopic(new String(topics, Charset.forName("utf-8")));

            //4. queueId
            int queueId = byteBuffer.getInt();
            messageExt.setQueueId(queueId);

            //5. 当前消息在queue队列中的个数
            long queueoffset = byteBuffer.getLong();
            messageExt.setQueueoffset(queueoffset);


            //6. 消息在commitlog文件中的物理位置
            long physicaloffset = byteBuffer.getLong();
            messageExt.setPhysicaloffset(physicaloffset);

            //7. 消息
            int bodyLength = byteBuffer.getInt();//4位
            if (bodyLength > 0) {
                byte[] datas = new byte[bodyLength];//totalsize
                byteBuffer.get(datas);//消息内容
                messageExt.setBody(datas);
            }
            //7. 存储时间
            long storeTimestamp = byteBuffer.getLong();
            messageExt.setStoreTimestamp(storeTimestamp);

            size += totalSize;
            list.add(messageExt);
        }

        return list;

    }

}
